﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using eTerm.MsSql.DbProvider;
using eTerm.Platform.Business;
using System.Text;

namespace eTerm.Platform.Web.ISAPI
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class uploadify : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            HttpPostedFile file =context.Request.Files["FileData"]; 
            string uploadpath = context. Server.MapPath(@"~\DetrUpload\"); 
            if (file != null) 
            { 
                //if (!Directory.Exists(uploadpath)) 
                //{ 
                //    Directory.CreateDirectory(uploadpath); 
                //} 
                //file.SaveAs(uploadpath + file.FileName);

                int? UID = int.Parse(context.User.Identity.Name);
                List<PnrDetr> items = new NPOIDetr(file.InputStream).ReadExcel(UID);
                StringBuilder sb = new StringBuilder(string.Format(@"{{
            ""total"":{0},
            ""rows"":
[",items.Count));
                foreach (PnrDetr i in items)
                {
                    i.Save();
                    sb.AppendFormat(@"{{""ID"":{0},""TicketNo"":""{1}"",""TicketDate"":""{2}""}},", i.Id, i.TicketNo, i.TicketDate.HasValue?i.TicketDate.Value.ToString(@"yyyy-MM-dd"):string.Empty);
                }

                if (items.Count > 1)
                    sb.Remove(sb.Length - 1, 1);
                sb.Append(@"]
            }");

                context.Response.Write(sb.ToString()); 
            } 
            else 
            { 
                context.Response.Write("0"); 
            } 
        } 

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
